package com.shopx.gw.interceptor;

import com.shopx.auth.DTO.LoginUserDTO;
import com.shopx.auth.service.ICheckAuthService;
import com.shopx.core.common.CommonConstant;
import com.shopx.core.context.ShopxContext;
import com.shopx.core.utils.StringUtil;
import com.shopx.gw.fliter.BodyReaderHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @author lituo
 * @className: BuildInterceptor
 * @description: TODO
 * @date 2021/12/2 1:59 PM
 */
@Slf4j
public class ShopxInterceptor implements HandlerInterceptor {

  @Value("${sys.name:sysname}")
  private String systemName;

  @Resource
  private ICheckAuthService checkAuthService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    String accessUrl = request.getServletPath();
    String trcId = StringUtil.createRandomCharData(32);
    ShopxContext ctx = ShopxContext.createAndPushContext();
    MDC.put(CommonConstant.TRACE_ID, trcId);
    if(accessUrl.indexOf("wxAccess")>-1 || accessUrl.indexOf("wxMini")>-1 || accessUrl.indexOf("error")>-1 || accessUrl.indexOf("oss/staticFile")>-1){
      //微信请求，直接放行
      return true;
    }
    String hmac = request.getHeader("hmac");
    if (StringUtil.isEmpty(hmac)) {
      //表单提交方式传递hamc
      hmac = request.getParameter("hmac");
    }
    //验证是否具有访问权限
    LoginUserDTO loginUserDTO = checkAuthService.checkLogin(accessUrl, hmac);
    if (loginUserDTO != null) {
      //存入上下文
      ctx.setProperty(CommonConstant.USER_ID, loginUserDTO.getUserId());
      ctx.setProperty(CommonConstant.CP_ID, loginUserDTO.getCpId());
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                         ModelAndView modelAndView) throws Exception {
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    String accessUrl = request.getServletPath();
    log.info("方法:{}执行结束。",accessUrl);
    MDC.remove(CommonConstant.TRACE_ID);
    ShopxContext ctx = ShopxContext.getCurrentContext();
    if (ctx != null) {
      // 清除上下文
      ctx.removeCurrentContext();
      ctx.clear();
    }
  }

  private String getParamString(Map<String, String[]> map) {
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String[]> e : map.entrySet()) {
      sb.append(e.getKey()).append("=");
      String[] value = e.getValue();
      if (value != null && value.length == 1) {
        sb.append(value[0]).append(" | ");
      } else {
        sb.append(Arrays.toString(value)).append(" | ");
      }
    }
    return sb.toString();
  }
}
